import json
import re

from django.contrib.auth import login, authenticate
from django.http import HttpResponse, JsonResponse

# Create your views here.
from django.views import View

from apps.user.models import User


class Register(View):
    def post(self, request):
        user_dict = json.loads(request.body)
        telephone = user_dict.get('telephone')
        password = user_dict.get('password')
        auth_code = user_dict.get('auth_code')

        if not all([telephone, password, auth_code]):
            return JsonResponse({'err': 400, 'errmsg': '缺少参数'})

        if not re.match(r'^1[345789]\d{9}$', telephone):
            return JsonResponse({'err': 400, 'errmsg': '手机号码错误'})

        if_user = User.objects.filter(mobile=telephone)
        print(if_user)
        if if_user:
            return JsonResponse({'err': 400, 'errmsg': '用户已存在'})

        user = User.objects.create_user(username=telephone, mobile=telephone, password=password)
        login(request, user)
        ret = JsonResponse({'err': 0, 'errmsg': 'OK'})
        # ret.set_cookie('')
        return ret


class Login(View):
    def post(self, request):
        user_dict = json.loads(request.body)
        # print(user_dict)
        mobile = user_dict.get('telephone')
        password = user_dict.get('password')

        if not all([mobile, password]):
            return JsonResponse({'err': 400, 'errmsg': '缺少参数'})

        if not re.match(r'^1[345789]\d{9}$', mobile):
            return JsonResponse({'err': 400, 'errmsg': '手机号码错误'})

        user = authenticate(username=mobile, password=password)
        if not user:
            return JsonResponse({'err': 400, 'errmsg': '用户名或密码错误'})

        login(request, user)

        ret = JsonResponse({'err': 0, 'errmsg': 'OK'})
        return ret

        return JsonResponse({'err': 0, 'errmsg': 'OK'})
